<?php

class ImageUploadForm extends CFormModel
{
	const IMG_PATH = '/upload/image/';
	
	public $file;
	
	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('file', 'file', 'types'=>'jpg, gif, png', 'allowEmpty'=>true),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
		);
	}

	public function saveUploadImage() {
		$file = $this->file;
		if (!$file) return;
		
		$fileName = time() .'-'. (string)$file;
		$dir = $this->getImageDir();
		$fullName = Yii::app()->basePath . '/..' . $dir . $fileName;
		
		@mkdir(Yii::app()->basePath . '/..' . $dir, 0777, true);
		$file->saveAs($fullName);
		$img = new Image();
		$img->path = $dir . $fileName;
		$img->save();
		return $dir . $fileName;
	}
	
	public function getImageDir() {
		return self::IMG_PATH . date('Y/m/d/');
	}
}